package handlers

import (
	"net/http"
	"strconv"
	"time"

	"things_iot_backend/auth"
	"things_iot_backend/database"
	"things_iot_backend/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type EventHandler struct {
	db *gorm.DB
}

func NewEventHandler(db *gorm.DB) *EventHandler {
	return &EventHandler{db: db}
}

// GetDeviceEvents 获取设备事件列表
func (h *EventHandler) GetDeviceEvents(c *gin.Context) {
	claims, exists := c.Get("claims")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权",
			"data":    nil,
		})
		return
	}

	userClaims := claims.(*auth.Claims)

	deviceID := c.Param("device_id")

	var device models.Device
	if err := h.db.Where("device_id = ?", deviceID).First(&device).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "设备不存在",
			"data":    nil,
		})
		return
	}

	// 检查权限
	if !auth.CanAccessDevice(userClaims, device.UserID) {
		c.JSON(http.StatusForbidden, gin.H{
			"code":    403,
			"message": "无权访问该设备事件",
			"data":    nil,
		})
		return
	}

	// 解析查询参数
	eventType := c.Query("event_type")
	startTimeStr := c.Query("start_time")
	endTimeStr := c.Query("end_time")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 20
	}

	// 解析时间范围
	startTime := time.Now().Add(-24 * time.Hour) // 默认最近24小时
	endTime := time.Now()

	if startTimeStr != "" {
		if t, err := time.Parse(time.RFC3339, startTimeStr); err == nil {
			startTime = t
		}
	}

	if endTimeStr != "" {
		if t, err := time.Parse(time.RFC3339, endTimeStr); err == nil {
			endTime = t
		}
	}

	// 获取事件列表
	events, total, err := database.GetDeviceEvents(device.ID, eventType, startTime, endTime, page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取事件列表失败",
			"data":    nil,
		})
		return
	}

	totalPages := (int(total) + pageSize - 1) / pageSize

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "success",
		"data": models.EventListResponse{
			Events: events,
			Pagination: models.PaginationResponse{
				Page:       page,
				PageSize:   pageSize,
				Total:      int(total),
				TotalPages: totalPages,
			},
		},
	})
}

// GetDeviceEventStats 获取设备事件统计
func (h *EventHandler) GetDeviceEventStats(c *gin.Context) {
	claims, exists := c.Get("claims")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权",
			"data":    nil,
		})
		return
	}

	userClaims := claims.(*auth.Claims)

	deviceID := c.Param("device_id")

	var device models.Device
	if err := h.db.Where("device_id = ?", deviceID).First(&device).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "设备不存在",
			"data":    nil,
		})
		return
	}

	// 检查权限
	if !auth.CanAccessDevice(userClaims, device.UserID) {
		c.JSON(http.StatusForbidden, gin.H{
			"code":    403,
			"message": "无权访问该设备统计",
			"data":    nil,
		})
		return
	}

	// 解析时间范围
	startTimeStr := c.Query("start_time")
	endTimeStr := c.Query("end_time")

	startTime := time.Now().Add(-24 * time.Hour) // 默认最近24小时
	endTime := time.Now()

	if startTimeStr != "" {
		if t, err := time.Parse(time.RFC3339, startTimeStr); err == nil {
			startTime = t
		}
	}

	if endTimeStr != "" {
		if t, err := time.Parse(time.RFC3339, endTimeStr); err == nil {
			endTime = t
		}
	}

	// 获取事件统计
	eventTypes, total, err := database.GetEventStats(device.ID, startTime, endTime)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取事件统计失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "success",
		"data": models.EventStatsResponse{
			TotalEvents: total,
			EventTypes:  eventTypes,
			Period: struct {
				StartTime time.Time `json:"start_time"`
				EndTime   time.Time `json:"end_time"`
			}{
				StartTime: startTime,
				EndTime:   endTime,
			},
		},
	})
}
